# 获取时间函数，把当前时间格式化为str类型nowdate.strftime('%Y-%m-%d %H:%M:%S')
import inspect
import json
from datetime import datetime
import tkinter as tk
from tkinter.messagebox import showwarning
import serial.tools.list_ports
from bases import match_method_dict
from commons.public_gobals import PublicGlobals
import os.path



file_ini_path = './datafiles/main_limit_args.json'
file_ini_dir = './datafiles'

def getLastDate():
    return datetime.now().strftime('%Y-%m-%d')

def getLastDateTime():
    return datetime.now().strftime('%Y-%m-%d %H:%M:%S')

def get_com():
    ports = serial.tools.list_ports.comports()
    for ins in sorted(ports):
        print(ins.device, end=' ')
        print(ins.pid, end=' ')
        print(ins.vid, end='\n')
        if ins.pid == 18005 and ins.vid == 13908:
            PublicGlobals.serial_handle_0 = ins.device
# def listKong2None(l:list):
#     for i in range(len(l)):
#         l[i] = l[i] if l[i] != '' else 'NAN'
#         print(l[i])

def args_file_is_exist() -> bool:
    return os.path.exists(file_ini_path)

def load_limit_args():
    if not args_file_is_exist():
        print('文件不存在，不加载')
        return
    try:
        from cases import main_cases        # 函数内引用，可以解决循环引用的问题，妙
        from windows import update_listview_GUI
        from commons import case_func_dict
        args_list: list | None = None
        with open(file_ini_path, 'r', encoding='utf-8') as f:
            args_list = json.load(f)
            for args, case in zip(args_list, main_cases):
                case.title = args['title']
                case.limit_H = args['limit_H']
                case.limit_L = args['limit_L']
                case.match_method = match_method_dict[args['match_method']]
                case.enable = args['enable']
                case.loop = args['loop']
                case.fresh_loop = args['fresh_loop']
                case.force_loop = args['force_loop']
                case.pre_time = args['pre_time']
                case.post_time = args['post_time']
                case.fail_time = args['fail_time']
                case.modify_flag = args['modify_flag']
                case.modify = args['modify']
                case.case_func = case_func_dict[args['case_func']]  # 实际保存为默认值，更新需要根据实际加载
                case.func_args_info = args['func_input_args']   # 刷新函数信息
                case.limit_args_2_global_value()                # 刷新limit_H信息
                case.update_func_args_info()                    # 更新函数参数信息
                # case.case_func = case_func_dict[args['case_func']]
        # print('123', 123123123)
        print('加载limit参数数据成功')
        update_listview_GUI.get()       # 触发tk变量，引起页面刷新
    except Exception as e:
        print('加载limit参数数据失败，原因为', e)
        showwarning(message='加载参数失败')

# 从字典的值中取键key
def dict_value_2_getkey(d:dict, data):
    for key, value in d.items():
        # 类型相同，且变量相同才可以获取键。python中默认1==True
        if type(data)==type(value) and (value == data or value is data):
            return key
    return None



# 获取函数参数的信息---名称，值，类型
def get_func_arg_default_type(func_ptr)->list[dict]:
    signature = inspect.signature(func_ptr)
    parameters = signature.parameters
    func_info:list[dict] = []
    # 接口被调用的函数的参数一定要类型和默认值
    for name, parameter in parameters.items():
        if parameter.default != inspect.Parameter.empty:
            print(f"{name}: {parameter.default}")
        annotation = parameter.annotation           # 从注解中获取参数类型
        param_type = annotation.__name__ if isinstance(annotation, type) else str(annotation)
        # print("参数：", name, "默认值：", parameter.default,"类型：", param_type)
        func_info.append({
            'name': name,
            'value': parameter.default,
            'type': param_type
        })
    return func_info
# 将函数信息转换成可以直接传入的**kwargs形式，与get_func_arg_default_type配套使用
def get_func_kwargs(func_info:list[dict]):
    kwargs_d = {}
    for arg_info in func_info:
        kwargs_d[arg_info['name']] = arg_info['value']
    return kwargs_d




def mac_conversation(hex_str:str, join_str:str=':'):
    """
    给MAC地址，中间添加符号用。使其看起来更直观.且对字符串进行大写处理
    :param hex_str:连续的MAC地址字符串(12位)
    :param join_str:连接的字符串。(梅2位的拼接在一起)，默认为 冒号(:)
    :return:用join_str字符串拼接的MAC。例如12:34:56:78:90:AB
    """
    hex_str = hex_str.replace(' ','')   # 清除字符串中的空格符
    hex_str = hex_str.upper()
    l = [hex_str[i:i + 2] for i in range(0, len(hex_str), 2)]
    res = join_str.join(l)
    # print(res)
    return res

def del_q_h_blank(s:str):
    """
    清除字符串前后的空格符
    :param s:输入的字符串
    :return:清除前后空格的字符串
    """
    return s.strip()

def get_module_func_dict(module, pre_char='',sep='_'):
    '''
    此函数用于获取一个模块中所有的函数，以引用的方式获取
    :param module:模块名
    :param pre_char:前置字符
    :param sep:中间间隔字符
    :return:字典，键对应的值为函数指针
    '''
    functions = [name for name in dir(module) if callable(getattr(module, name))]
    # print(functions)
    # print(module.__dict__)
    d = {}
    for key, value in module.__dict__.items():
        if key in functions:
            d[pre_char+sep+str(key)] = value
    # print(d)
    return d
    # print(d['add'](1, 2))


def get_PB130_module_func_dict():
    # from test_py import PB130_function
    # from commons import case_func_dict
    # d = get_module_func_dict(PB130_function, 'PB130', '_')
    # case_func_dict.update(d)
    pass



